﻿using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.SessionState;
using System.Text;
using Watson.Core.Tools;
using InfoSoftGlobal;
using ITOMMS.Entity;
using System.Collections.Generic;

namespace ITOMMS.Web.Ajax
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ReportService : IHttpHandler, IReadOnlySessionState, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //不让浏览器缓存 
            context.Response.Buffer = true;
            context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            string flag = context.Request.Form["flag"];
            switch (flag)
            {

                //为显示的div的id
                case ("troubleOfYear"):
                    try
                    {
                        string year = context.Request.Form["year"];
                        string customer = context.Request.Form["customer"];
                        context.Response.Write(getTourbleFormReportHtml(customer, year));
                    }
                    catch (Exception ex)
                    {
                        log4netHelper.error("报表出错", ex);
                        return;
                    }

                    break;
                case ("troubleOfWeek"):
                    try
                    {
                        string year = context.Request.Form["year"];
                        string customer = context.Request.Form["customer"];
                        DateTime rs = new DateTime();
                        if (DateTime.TryParse(year, out  rs))
                        {
                            context.Response.Write(getTourbleFormReportWeek(customer, rs));
                        }
                        else
                        {
                            context.Response.Write("");
                        }

                    }
                    catch (Exception ex)
                    {
                        log4netHelper.error("报表出错", ex);
                        return;
                    }

                    break;



            }

        }


        #region 收入支出统计图 参考
        public string getSRZCThtml(string year, string month)
        {
            try
            {
                decimal shrouruMoney = 10;//收入金额
                decimal zhichuMoney = 20;//支出金额
                decimal jieyuMoney = 40;//结余金额


                //DataSet ds = atAccService.GetReportListByMonth(year, month);
                //if (ds.Tables[0].Rows.Count > 0)
                //{
                //    foreach (DataRow dr in ds.Tables[0].Rows)
                //    {
                //        if (dr["typeName"].ToString() == "收入")
                //        {
                //            shrouruMoney = decimal.Parse(dr["Amount"].ToString());
                //        }
                //        else if (dr["typeName"].ToString() == "支出")
                //        {
                //            if (decimal.Parse(dr["Amount"].ToString()) > 0)
                //            {
                //                zhichuMoney = decimal.Parse("-" + dr["Amount"].ToString());
                //            }
                //            else
                //            {
                //                zhichuMoney = decimal.Parse(dr["Amount"].ToString());
                //            }
                //        }
                //    }
                //}
                jieyuMoney = shrouruMoney + zhichuMoney;

                //生成图形状的 html
                StringBuilder xmlData = new StringBuilder();
                xmlData.Append("<chart caption='月度财务状况' animation='1'  showValues='0' formatNumberScale='0' showBorder='0'>");
                xmlData.Append("<set label='收入' value='" + shrouruMoney + "' />");
                xmlData.Append("<set label='支出' value='" + zhichuMoney + "' />");
                xmlData.Append("<set label='结余' value='" + jieyuMoney + "' />");
                xmlData.Append("</chart>");
                // return FusionCharts.RenderChartHTML("../../Flash/Column2D.swf", "", xmlData.ToString(), "myNext", "400", "180", false);

                return FusionCharts.RenderChartHTML("../../Flash/Column3D.swf", "", xmlData.ToString(), "myNext", "350", "180", false);

            }
            catch
            {
                return "1";
            }

        }
        #endregion



        #region 故障报表按年月
        /// <summary>
        /// 按年查询出故障报表
        /// //参考:http://www.fusioncharts.com/Gallery/Category.asp?Column3D
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        public string getTourbleFormReportHtml(string customer, string QueryYear)
        {
            string startDate = QueryYear + "-01-01";
            string endData = QueryYear + "-12-31";


            List<tbTroubleClassEntity> tcList = new List<tbTroubleClassEntity>();
            tcList = new ITOMMS.Entity.tbTroubleClassEntity().GetAll();

            DataSet ds = new DataSet();
            if (customer == "-1")
            {
                ds = new tbTroubleClassEntity().GetDataSet("   SELECT DATEPART(month, RequestTime) AS mymonth FROM   Vw_TroubleForm  WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "'    GROUP BY DATEPART(month, RequestTime) ");
            }
            else
            {
                ds = new tbTroubleClassEntity().GetDataSet("   SELECT DATEPART(month, RequestTime) AS mymonth FROM   Vw_TroubleForm  WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "' and OwnerCompnayID=" + customer + "   GROUP BY DATEPART(month, RequestTime) ");
            }
            DataSet dstemp = new DataSet();

            try
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("   <chart caption='" + QueryYear.ToString() + "年每月故障统计报表' XAxisName='按月份和类别统计' palette='2' animation='1' formatNumberScale='0' numberPrefix='' numberSuffix='次'  showValues='0' numDivLines='4' legendPosition='BOTTOM'>  ");

                //月份
                sb.Append("                  <categories>  ");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    sb.Append("                  <category label='" + dr[0] + "月' />   ");
                }

                sb.Append("                  </categories>  ");

                //类别
                foreach (tbTroubleClassEntity tc in tcList)
                {
                    sb.Append("                  <dataset seriesName='" + tc.ClassName + "'>  ");
                    foreach (DataRow drr in ds.Tables[0].Rows)
                    {
                        //对应月份的值
                        if (customer == "-1")
                        {
                            dstemp = new tbTroubleClassEntity().GetDataSet("    SELECT COUNT(ID) AS num FROM   Vw_TroubleForm WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "'        AND className = '" + tc.ClassName + "' AND DATEPART(month, RequestTime)= " + drr[0]);
                        }
                        else
                        {
                            dstemp = new tbTroubleClassEntity().GetDataSet("    SELECT COUNT(ID) AS num FROM   Vw_TroubleForm WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "'        AND className = '" + tc.ClassName + "' AND DATEPART(month, RequestTime)= " + drr[0] + "    and OwnerCompnayID=" + customer);
                        }
                        sb.Append("                  <set value='" + dstemp.Tables[0].Rows[0][0] + "' />   ");

                    }
                    sb.Append("                  </dataset>  ");
                }

                sb.Append("                  <styles>  ");
                sb.Append("                  <definition>  ");
                sb.Append("                  <style type='font' name='CaptionFont' color='666666' size='15' />   ");
                sb.Append("                  <style type='font' name='SubCaptionFont' bold='0' />   ");
                sb.Append("                  </definition>  ");
                sb.Append("                  <application>  ");
                sb.Append("                    <apply toObject='caption' styles='CaptionFont' />   ");
                sb.Append("                    <apply toObject='SubCaption' styles='SubCaptionFont' />   ");
                sb.Append("                    </application>  ");
                sb.Append("                    </styles>  ");
                sb.Append("                    </chart>  ");

                return FusionCharts.RenderChartHTML("../Flash/MSColumn3D.swf", "", sb.ToString(), "myNext", "350", "350", false);

            }
            catch
            {
                return "1";
            }

        }
        #endregion


        #region 故障报表按月周
        /// <summary>
        /// 故障报表按月周
        /// //参考:http://www.fusioncharts.com/Gallery/Category.asp?Column3D
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        public string getTourbleFormReportWeek(string customer, DateTime datetime)
        {

            int days = 0;
            days = System.DateTime.DaysInMonth(datetime.Year, datetime.Month);

            string startDate = datetime.Year + "-" + datetime.Month.ToString() + "-01";
            string endData = datetime.Year + "-" + datetime.Month.ToString() + "-" + days.ToString();


            List<tbTroubleClassEntity> tcList = new List<tbTroubleClassEntity>();
            tcList = new ITOMMS.Entity.tbTroubleClassEntity().GetAll();

            //查出有几周
            DataSet ds = new DataSet();
            if (customer == "-1")
            {
                ds = new tbTroubleClassEntity().GetDataSet("   SELECT DATEPART(week, RequestTime) AS myweek FROM   Vw_TroubleForm  WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "'   GROUP BY DATEPART(week, RequestTime) ");
            }
            else
            {
                ds = new tbTroubleClassEntity().GetDataSet("   SELECT DATEPART(week, RequestTime) AS myweek FROM   Vw_TroubleForm  WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "'  and OwnerCompnayID=" + customer + "  GROUP BY DATEPART(week, RequestTime) ");
            }
            DataSet dstemp = new DataSet();

            try
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("   <chart caption='" + datetime.ToString("yyyy年MM") + "月份每周故障统计报表' XAxisName='按周和类别统计' palette='2' animation='1' formatNumberScale='0' numberPrefix='' numberSuffix='次'  showValues='0' numDivLines='4' legendPosition='BOTTOM'>  ");

                //月份
                sb.Append("                  <categories>  ");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    sb.Append("                  <category label='" + dr[0] + "周' />   ");
                }

                sb.Append("                  </categories>  ");

                //类别
                foreach (tbTroubleClassEntity tc in tcList)
                {
                    sb.Append("                  <dataset seriesName='" + tc.ClassName + "'>  ");
                    foreach (DataRow drr in ds.Tables[0].Rows)
                    {
                        //对应月份的值
                        if (customer == "-1")
                        {
                            dstemp = new tbTroubleClassEntity().GetDataSet("    SELECT COUNT(ID) AS num FROM   Vw_TroubleForm WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "'        AND className = '" + tc.ClassName + "' AND DATEPART(week, RequestTime)= " + drr[0]);
                        }
                        else
                        {
                            dstemp = new tbTroubleClassEntity().GetDataSet("    SELECT COUNT(ID) AS num FROM   Vw_TroubleForm WHERE  RequestTime BETWEEN '" + startDate + "' AND '" + endData + "'        AND className = '" + tc.ClassName + "' AND DATEPART(week, RequestTime)= " + drr[0] + " and OwnerCompnayID=" + customer);
                        }
                        sb.Append("                  <set value='" + dstemp.Tables[0].Rows[0][0] + "' />   ");

                    }
                    sb.Append("                  </dataset>  ");
                }

                sb.Append("                  <styles>  ");
                sb.Append("                  <definition>  ");
                sb.Append("                  <style type='font' name='CaptionFont' color='666666' size='15' />   ");
                sb.Append("                  <style type='font' name='SubCaptionFont' bold='0' />   ");
                sb.Append("                  </definition>  ");
                sb.Append("                  <application>  ");
                sb.Append("                    <apply toObject='caption' styles='CaptionFont' />   ");
                sb.Append("                    <apply toObject='SubCaption' styles='SubCaptionFont' />   ");
                sb.Append("                    </application>  ");
                sb.Append("                    </styles>  ");
                sb.Append("                    </chart>  ");

                return FusionCharts.RenderChartHTML("../Flash/MSColumn3D.swf", "", sb.ToString(), "myNext", "350", "350", false);

            }
            catch
            {
                return "1";
            }

        }
        #endregion






        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 直接得到当天是当月的第几周 dtSel:要判断的日期,sundayStart：一周的第一天是否为周日
        /// </summary>
        /// <param name="dtSel">要判断的日期</param>
        /// <param name="sundayStart">一周的第一天是否为周日</param>
        /// <returns></returns>
        public static int WeekOfMonth(DateTime dtSel, bool sundayStart)
        {
            //如果要判断的日期为1号，则肯定是第一周了
            if (dtSel.Day == 1)
                return 1;
            else
            {
                //得到本月第一天
                DateTime dtStart = new DateTime(dtSel.Year, dtSel.Month, 1);
                //得到本月第一天是周几
                int dayofweek = (int)dtStart.DayOfWeek;

                //如果不是以周日开始，需要重新计算一下dayofweek，详细风DayOfWeek枚举的定义
                if (!sundayStart)
                {
                    dayofweek = dayofweek - 1;

                    if (dayofweek < 0)
                        dayofweek = 7;
                }

                //得到本月的第一周一共有几天
                int startWeekDays = 7 - dayofweek;

                //如果要判断的日期在第一周范围内，返回1
                if (dtSel.Day <= startWeekDays)
                    return 1;
                else
                {
                    int aday = dtSel.Day + 7 - startWeekDays;
                    return aday / 7 + (aday % 7 > 0 ? 1 : 0);
                }
            }
        }


    }
}
